namespace EFS.EventLog
{
	public class Counter
	{
		// Sink
		private static object sink = new object();

		// Add information
		public static void LogCounter(System.String counterName)
		{
			if (EFS.EventLog.Config.Log.FileLog.Filter.Counter)
			{
				WriteCounter(counterName);
			}
		}

		/// <summary>
		/// Log entry count
		/// </summary>
		/// <param name="message"></param>
		/// <param name="logType"></param>
		private static void WriteCounter(System.String counterName)
		{	
			// create filename
			string counterFile = EFS.EventLog.Config.Log.FileLog.FilePath + "" + counterName + ".counter.txt";

			lock (sink)
			{
				try
				{					
					// get counter and increment
					System.Int32 cnt = GetCounter(counterFile) + 1;

					// open file to write
					System.IO.StreamWriter sw = new System.IO.StreamWriter(counterFile, false);

					// write counter
					sw.Write(cnt.ToString());

					// close
					sw.Close();
				}
				catch (System.Exception e)
				{
					System.Diagnostics.Debug.WriteLine(e);
				}
			}
		}

		/// <summary>
		/// Get counter
		/// </summary>
		/// <param name="counterFile"></param>
		/// <returns></returns>
		private static System.Int32 GetCounter(System.String counterFile)
		{
			System.Int32 cnt = 0;
			System.String count=null;

			lock (sink)
			{
				try
				{
					// open file read counter
					System.IO.StreamReader sr = new System.IO.StreamReader(counterFile, true);
					count = sr.ReadLine();
					sr.Close();
				}
				catch (System.Exception e)
				{
					System.Diagnostics.Debug.WriteLine(e);
				}

				System.Int32.TryParse(count, out cnt);

				return cnt;
			}
		}
	}
}